//
//  KLAuthorizationTVC.m
//  KISSLOCK
//
//  Created by 陈宾鹏 on 17/3/23.
//  Copyright © 2017年 陈宾鹏. All rights reserved.
//

#import "KLAuthorizationTVC.h"
#import "KLHelp.h"
#import "KLHttpAPI.h"
#import "HemaConst.h"
#import "JRToast.h"
#import "Masonry.h"
#import <AddressBookUI/ABPeoplePickerNavigationController.h>
#import <AddressBook/ABPerson.h>
#import <AddressBookUI/ABPersonViewController.h>
#import "WSDatePickerView.h"
#import "BeeCloud.h"
#import "UIAlertView+Blocks.h"
#import "KLRechargeViewController.h"
#import "BuleFuction.h"
#import "NSData+hex.h"
#import "HemaFunction.h"

@interface KLAuthorizationTVC ()<UITextFieldDelegate,ABPeoplePickerNavigationControllerDelegate,BeeCloudDelegate,UIActionSheetDelegate>
{
    BOOL isSelect;//是否同时授权二级锁主
}
@property(nonatomic,strong) UIView *headView;
@property(nonatomic,strong) UITextField *mobileField;
@property(nonatomic,strong) UIButton *mobileListBtn;
@property(nonatomic,strong) UIImageView *secondLockMaster;
@property(nonatomic,strong) UIButton *sendBrunch;

@property(nonatomic,strong)NSString *money;
@property(nonatomic,strong)NSString *totalFee;
@property(nonatomic,strong)NSString *trade_no;
@end

@implementation KLAuthorizationTVC
-(UIImageView *)secondLockMaster{
    if(!_secondLockMaster){
        _secondLockMaster = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"未选"]];
        isSelect = NO;
    }
    return _secondLockMaster;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.tableView.tableFooterView = [UIView new];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.navigationItem.title = @"授权二级钥匙串";
    [KLHelp navSet:self doBackHandeler:^(UIButton *backButton) {
        [backButton addTarget:self action:@selector(doBack:) forControlEvents:UIControlEventTouchUpInside];
    }];
    //刷新钥匙串里的所有数据
    [self getCurrentBrunch];
    //UITableView的头视图
    self.headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, UI_View_Width, 70)];
    self.headView.backgroundColor = [UIColor whiteColor];
    self.tableView.tableHeaderView = self.headView;
    //输入手机号
    self.mobileField = [[UITextField alloc]init];
    self.mobileField.placeholder = @"请输入对方手机号";
    self.mobileField.borderStyle = UITextBorderStyleRoundedRect;
    self.mobileField.keyboardType = UIKeyboardTypeNumberPad;
    [self.headView addSubview:self.mobileField];
    [self.mobileField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.top.mas_equalTo(20);
        make.height.mas_equalTo(30);
        make.right.mas_equalTo(-70);
    }];
    //点击进入通讯录按钮
    self.mobileListBtn = [[UIButton alloc]init];
    [self.mobileListBtn setBackgroundImage:[UIImage imageNamed:@"通讯录"] forState:UIControlStateNormal];
    [self.mobileListBtn addTarget:self action:@selector(selectMobileList:) forControlEvents:UIControlEventTouchUpInside];
    [self.headView addSubview:self.mobileListBtn];
    [self.mobileListBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-20);
        make.top.mas_equalTo(20);
        make.width.mas_equalTo(30);
        make.height.mas_equalTo(30);
    }];
    //发送按钮
    self.sendBrunch = [[UIButton alloc]initWithFrame:CGRectMake(20, UI_View_Height/4, UI_View_Width-40, 40)];
    [self.sendBrunch setTitle:@"发送" forState:UIControlStateNormal];
    self.sendBrunch.titleLabel.font = [UIFont systemFontOfSize:19 weight:0.6];
    self.sendBrunch.layer.masksToBounds = YES;
    self.sendBrunch.layer.cornerRadius = 5.f;
    self.sendBrunch.backgroundColor = [KLHelp mainBlueColor];
    [self.sendBrunch addTarget:self action:@selector(sendBrunchKeys:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.sendBrunch];
    
}-(void)doBack:(UIButton *)sender{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"authorizationBrunch"];
    if(!cell){
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"authorizationBrunch"];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    //添加已选图片
    [cell.contentView addSubview:self.secondLockMaster];
    [self.secondLockMaster mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.width.and.height.mas_equalTo(20);
        make.centerY.equalTo(cell.contentView);
    }];
    UILabel *label = [[UILabel alloc]init];
    label.text = @"同时授权二级锁主";
    label.font = [UIFont systemFontOfSize:16];
    [cell.contentView addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(45);
        make.centerY.equalTo(cell.contentView);
    }];
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    isSelect = !isSelect;
    if(isSelect){
        self.secondLockMaster.image = [UIImage imageNamed:@"选中"];
    }else{
        self.secondLockMaster.image = [UIImage imageNamed:@"未选"];
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 40.f;
}

#pragma mark -刷新钥匙串里的数据
-(void)getCurrentBrunch{
    [KLHelp showHUDAddedTo:self.view animated:YES];
    [KLHttpAPI requestAllLocksOfBrunchWithID:[self.groupDic objectForKey:@"id"] type:[self.groupDic objectForKey:@"type"] completionHandler:^(MKNetworkOperation *operation) {
        [KLHelp hideAllHUDsForView:self.view animated:YES];
        NSLog(@"获取一个钥匙串里的所有锁数据：%@",operation.responseString);
        NSDictionary *dic = operation.responseJSON;
        NSString *isSuccess = [dic objectForKey:@"success"];
        if(isSuccess.integerValue == 1){
            self.groupDetailArr = [dic objectForKey:@"infor"];
        }else{
            [JRToast showWithText:[dic objectForKey:@"msg"]];
            [self.navigationController popViewControllerAnimated:YES];
        }
    } errorHandler:^(NSString *error) {
        [KLHelp hideAllHUDsForView:self.view animated:YES];
        [JRToast showWithText:error];
        [self.navigationController popViewControllerAnimated:YES];
    }];
}

-(void)selectMobileList:(UIButton *)sender{
    //调取通讯录
    [KLHelp showHUDAddedTo:self.view animated:YES];
    ABPeoplePickerNavigationController *nav = [[ABPeoplePickerNavigationController alloc] init];
    nav.peoplePickerDelegate = self;
    
    //这个变量用于记录授权是否成功，即用户是否允许我们访问通讯录
    int __block tip=0;
    //声明一个通讯簿的引用
    ABAddressBookRef addBook =nil;
    //因为在IOS6.0之后和之前的权限申请方式有所差别，这里做个判断
    if ([[UIDevice currentDevice].systemVersion floatValue]>=6.0) {
        //创建通讯簿的引用
        addBook=ABAddressBookCreateWithOptions(NULL, NULL);
        //创建一个出事信号量为0的信号
        dispatch_semaphore_t sema=dispatch_semaphore_create(0);
        //申请访问权限
        ABAddressBookRequestAccessWithCompletion(addBook, ^(bool greanted, CFErrorRef error)        {
            //greanted为YES是表示用户允许，否则为不允许
            if (!greanted) {
                tip=1;
            }else{
                if([[UIDevice currentDevice].systemVersion floatValue] >= 8.0){
                    nav.predicateForSelectionOfPerson = [NSPredicate predicateWithValue:false];
                }
                [self presentViewController:nav animated:YES completion:nil];
                [KLHelp hideAllHUDsForView:self.view animated:YES];
            }
            //发送一次信号
            dispatch_semaphore_signal(sema);
        });
        //等待信号触发
        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
    }else{
        //IOS6之前
        addBook =ABAddressBookCreate();
    }
}

#pragma mark - 选择通讯录列表的代理方法
//取消选择
- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker{
    [peoplePicker dismissViewControllerAnimated:YES completion:nil];
}

- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier {
    ABMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty);
    long index = ABMultiValueGetIndexForIdentifier(phone,identifier);
    NSString *phoneNO = (__bridge NSString *)ABMultiValueCopyValueAtIndex(phone, index);
    
    if ([phoneNO hasPrefix:@"+"]) {
        phoneNO = [phoneNO substringFromIndex:3];
    }
    phoneNO = [phoneNO stringByReplacingOccurrencesOfString:@"-" withString:@""];
    
    self.mobileField.text = phoneNO;
    
    [peoplePicker dismissViewControllerAnimated:YES completion:nil];
}

- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController*)peoplePicker didSelectPerson:(ABRecordRef)person{
    ABPersonViewController *personViewController = [[ABPersonViewController alloc] init];
    personViewController.displayedPerson = person;
    [peoplePicker pushViewController:personViewController animated:YES];
}

#pragma mark - 点击发送钥匙串
-(void)sendBrunchKeys:(UIButton *)sender{
    if(![HemaFunction xfunc_isMobileNumber:self.mobileField.text]){
        [KLHelp showTextHUDforView:self.view text:@"请输入正确的手机号"];
        return;
    }
    //钥匙串的有效期
    NSString *startDate = @"0";
    NSString *endDate = @"0";
    NSString *style = [self.groupDic objectForKey:@"type"];
    NSString *group_id = [self.groupDic objectForKey:@"group_id"];
    //是否同时授权二级锁主
    NSString *authorize;
    if(isSelect)
        authorize = @"1";
    else
        authorize = @"0";
    //先获取钥匙串的价格
    [self getGroupTotalFeeWithStartDate:startDate endDate:endDate style:style authorize:authorize group_id:group_id];
}

#pragma mark - 获取钥匙串的费用
-(void)getGroupTotalFeeWithStartDate:(NSString *)startDate endDate:(NSString *)endDate style:(NSString *)style authorize:(NSString *)authorize group_id:(NSString *)group_id{
    [KLHelp showHUDAddedTo:self.view animated:YES];
    [KLHttpAPI getKeyGroupTotalFeeWithStartDate:startDate endDate:endDate style:style authorize:authorize group_id:group_id power:@"02" completionHandler:^(MKNetworkOperation *operation) {
        [KLHelp hideAllHUDsForView:self.view animated:YES];
        NSDictionary *dic = operation.responseJSON;
        NSLog(@"获取钥匙串费用为:%@",dic);
        NSString *isSuccess = [dic objectForKey:@"success"];
        if(isSuccess.integerValue == 1){
            self.totalFee = [dic objectForKey:@"infor"];
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"此次操作支付:¥ %@元",self.totalFee]
                                                            message:nil
                                                   cancelButtonItem:[RIButtonItem itemWithLabel:@"取消" action:nil]
                                                   otherButtonItems:[RIButtonItem itemWithLabel:@"确定" action:^{
                NSString *amount = [[NSUserDefaults standardUserDefaults] objectForKey:@"feeaccount"];
                NSLog(@"amount:%@",amount);
                if(amount.doubleValue < self.totalFee.doubleValue){
                    UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:@"当前余额不足" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"充值",@"在线支付", nil];
                    [sheet showInView:self.view];
                }else
                    [self sendGroupBrunchWithStartDate:startDate endDate:endDate style:style authorize:authorize group_id:group_id totalFee:self.totalFee];
            }], nil];
            [alert show];
        }else{
            [JRToast showWithText:[dic objectForKey:@"msg"]];
        }
    } errorHandler:^(NSString *error) {
        [JRToast showWithText:error];
    }];
}

#pragma mark - 发送钥匙的网络请求
-(void)sendGroupBrunchWithStartDate:(NSString *)startDate endDate:(NSString *)endDate style:(NSString *)style authorize:(NSString *)authorize group_id:(NSString *)group_id totalFee:(NSString *)totalfee{
    NSString *from_id = [self.groupDic objectForKey:@"id"];
    NSMutableArray *lockinfor = [NSMutableArray array];
    NSString *userAesKey;
    NSString *rsaKey;
    if (style.integerValue == 1){
        for (NSDictionary *dic in self.groupDetailArr) {
            NSString *lock_id = [dic objectForKey:@"lock_id"];
            userAesKey = [KLHelp getUserSixTeenRandomAESKey];
            rsaKey = [KLHelp getLockRSAPublicKeyWithLockName:[dic objectForKey:@"uname"]];
            if(rsaKey.length == 0){
                [KLHelp showTextHUDforView:self.view text:@"公钥丢失，请重新扫描二维码！"];
                return ;
            }
            NSData *packageChildKey = [BuleFuction packChildkeyToData:rsaKey mobileStr:self.mobileField.text startTime:@"000000000000" endTime:@"000000000000" commondCode:@"0" userAESKey:userAesKey];
            rsaKey = [packageChildKey convertDataToHexStr:packageChildKey];
            NSMutableDictionary *mutableDic = [NSMutableDictionary dictionary];
            [mutableDic setObject:lock_id forKey:@"lock_id"];
            [mutableDic setObject:rsaKey forKey:@"rsa"];
            [mutableDic setObject:userAesKey forKey:@"aes"];
            [lockinfor addObject:mutableDic];
        }
    }else{
        for (NSDictionary *dic in self.groupDetailArr) {
            NSString *lock_id = [dic objectForKey:@"lock_id"];
            NSMutableDictionary *mutableDic = [NSMutableDictionary dictionary];
            [mutableDic setObject:lock_id forKey:@"lock_id"];
            [mutableDic setObject:@"" forKey:@"rsa"];
            [mutableDic setObject:@"" forKey:@"aes"];
            [lockinfor addObject:mutableDic];
        }
    }
    
    [KLHelp showHUDAddedTo:self.view animated:YES];
    [KLHttpAPI new_requestSendLockGroupWithStyle:style power:@"02" lockinfor:lockinfor Command_code:@"a1" group_id:group_id mobile:self.mobileField.text enddate:endDate startdate:startDate updatetime:@"10000" totalfee:totalfee from_id:from_id authorize:authorize completionHandler:^(MKNetworkOperation *operation) {
        [KLHelp hideAllHUDsForView:self.view animated:YES];
        NSLog(@"发送钥匙串返回数据:%@",operation.responseString);
        NSDictionary *dic = operation.responseJSON;
        [KLHelp showTextHUDforView:self.view text:[dic objectForKey:@"msg"]];
    } errorHandler:^(NSString *error) {
        [KLHelp hideAllHUDsForView:self.view animated:YES];
        [KLHelp showTextHUDforView:self.view text:error];
    }];
}

#pragma mark - UIActionSheetDelegate
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    NSLog(@"%zd",buttonIndex);
    if(buttonIndex == 0){//充值
        KLRechargeViewController *rechargeVC = [[KLRechargeViewController alloc]init];
        [self.navigationController pushViewController:rechargeVC animated:YES];
    }else if(buttonIndex == 1){//在线支付
        //设置支付代理
        self.money = [NSString stringWithFormat:@"%.f",self.totalFee.doubleValue * 100];
        [BeeCloud setBeeCloudDelegate:self];
        //充值
        [self recharge];
    }
}

-(void)recharge{
    //本机当前时间(用于自定义单号)
    NSDate *  senddate=[NSDate date];
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYYMMddHHmmss"];
    NSString *locationString=[dateformatter stringFromDate:senddate];
    
    //支付请求
    [BeeCloud initWithAppID:@"1e70e317-1286-490b-ad3b-3d56f8f2e0a0" andAppSecret:@"caf7da3a-1b60-499c-920c-5d0c2008693a"];
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:self.money,[[NSUserDefaults standardUserDefaults] objectForKey:@"phoneNumber"], nil];
    /**
     按住键盘上的option键，点击参数名称，可以查看参数说明
     **/
    BCPayReq *payReq = [[BCPayReq alloc] init];
    payReq.channel = PayChannelAliApp; //支付渠道
    payReq.title = @"KISSLOCK蓝牙锁在线支付";//订单标题
    payReq.totalFee = [NSString stringWithFormat:@"%@",self.money];//订单价格
    self.trade_no = [NSString stringWithFormat:@"0002%@%@",locationString,[[NSUserDefaults standardUserDefaults] objectForKey:@"phoneNumber"]];
    payReq.billNo = self.trade_no;//商户自定义订单号
    payReq.scheme = @"prefsGuoYangKissLock";//URL Scheme,在Info.plist中配置; 支付宝必有参数
    payReq.billTimeOut = 300;//订单超时时间
    payReq.viewController = self; //银联支付和Sandbox环境必填
    payReq.optional = dict;//商户业务扩展参数，会在webhook回调时返回
    [BeeCloud sendBCReq:payReq];
}

#pragma mark - BCPay回调
- (void)onBeeCloudResp:(BCBaseResp *)resp {
    if(resp.type == BCObjsTypePayResp){
        // 支付请求响应
        BCPayResp *tempResp = (BCPayResp *)resp;
        if (tempResp.resultCode == 0) {
            NSLog(@"支付情况：%@",resp.resultMsg);
            [KLHttpAPI payoffSuccessWithKeytype:@"1" total_fee:self.money trade_no:self.trade_no completionHandler:^(MKNetworkOperation *operation) {
                NSLog(@"充值返回数据：%@",operation.responseString);
                NSDictionary *dic = operation.responseJSON;
                NSString *isSuccess = [dic objectForKey:@"success"];
                if(isSuccess.integerValue == 1){
                    [[NSUserDefaults standardUserDefaults] setObject:[dic objectForKey:@"msg"] forKey:@"feeaccount"];
                    NSString *style = [self.groupDic objectForKey:@"type"];
                    NSString *group_id = [self.groupDic objectForKey:@"group_id"];
                    //是否同时授权二级锁主
                    NSString *authorize = @"0";
                    [self sendGroupBrunchWithStartDate:@"0" endDate:@"0" style:style authorize:authorize group_id:group_id totalFee:self.totalFee];
                }else{
                    [KLHelp showTextHUDforView:self.view text:@"充值失败"];
                }
            } errorHandler:^(NSString *error) {
                [KLHelp showTextHUDforView:self.view text:@"充值失败"];
            }];
        } else {
            //支付取消或者支付失败
            NSLog(@"支付取消或失败结果信息:resultMsg：%@, errDetail：%@, type：%zd, resultCode：%zd",tempResp.resultMsg,tempResp.errDetail,tempResp.request.type,tempResp.resultCode);
        }
    }
}

@end
